﻿using AutoMapper;
using MaterialTypeRecognition.Shell.MesServices;
using MaterialTypeRecognition.Shell.SaveInfos;
using MaterialTypeRecognition.Shell.SaveInfoService;
using MaterialTypeRecognition.Shell.Utils;
using Microsoft.AspNetCore.Mvc;
using Prism.Events;
using System.Threading.Tasks;

namespace MaterialTypeRecognition.Shell.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class MesServiceController : ControllerBase
    {
        private readonly IInBoundMesService _inboundService;

        private readonly ISaveInfoService _saveInfoService;

        private readonly IMapper _mapper;

        private readonly IEventAggregator _eventAggregator;

        public MesServiceController(IInBoundMesService inboundMesService, ISaveInfoService saveInfoService, IMapper mapper, IEventAggregator eventAggregator)
        {
            _saveInfoService = saveInfoService;
            _inboundService = inboundMesService;
            _mapper = mapper;
            _eventAggregator = eventAggregator;
        }

        [HttpGet]
        public async Task<StartResponseMessageDto> InBound(string sfc)
        {
            var mesConfig = await _saveInfoService.ReadAsync<MesConfigurationSaveInfo>();
            var requestMessage = _mapper.Map<StartRequestMessageDto>(mesConfig);
            requestMessage.Sfc = sfc;
            var result = await _inboundService.PostAsync(requestMessage);
            _eventAggregator.GetEvent<InBoundEvent>().Publish(new InBoundEventArgs(result.Success, result.Message, sfc));
            return result;
        }
    }
}
